<?php

App::uses('AdminController', 'Controller');
App::uses('Receipe', 'Model');

class AdminReceipesController extends AdminController {
	
	public $uses = array("Receipe", "Product");
	
	public $paginate = array(
		'limit' => ITEMS_PER_PAGE,
		'order' => 'id DESC'
	);
	
	public function index() {
		$this->set("receipes", $this->paginate('Receipe'));
	}
	
	public function create() {
		$this->set("receipe", $this->Receipe->create());
		$this->render('form');
	}

	public function edit($id) {
		$this->set("receipe", $this->Receipe->findById($id));
		$this->render('form');
	}
	
	public function save() {
		if(!empty($this->data)) {
			$data = $this->data;
			
			$toupload = false;
			if(!$data['Receipe']['file']['error']) {
				$data['Receipe']['image'] = $data['Receipe']['file']['name'];
				$toupload = $data['Receipe']['file'];
			}
			
			$this->Receipe->set($data);
			if($this->Receipe->validates()) {
                $this->Receipe->deleteRelatedData();
				if($this->Receipe->saveAll($data)) {
					if($toupload) {
						upload($toupload['tmp_name'], 'img' . DS . 'recepti' . DS . $toupload['name']);
					}
					
					$this->setFlash("Recept je sačuvan.", "ok");
					$this->redirect('/admin_receipes/edit/'.$this->Receipe->id);
				}else{
					$this->setFlash("Čuvanje nije uspelo.");
					return $this->render("form");
				}
			}else{
				$this->setFlash("Uneti podaci nisu validni.");
				return $this->render("form");
			}
		}
		$this->redirect("index");
	}
	
	public function search($kword) {
		$this->autoRender = false;
		
		$receipes = array();
		$conditions = array("Receipe.title LIKE" => "%$kword%");
		if(!empty($this->data['receipe_ids'])) {
			$conditions["Receipe.id NOT"] = $this->data['receipe_ids'];
		}
		
		if($receipes = $this->Receipe->find("all", array(
			"conditions" => $conditions,
			"fields" => array("Receipe.id", "Receipe.title", "Receipe.image")
		))) {
			$receipes = Set::extract('{n}.Receipe', $receipes);
		}
		
		echo json_encode($receipes);
	}
	
	public function search_products() {
		$this->autoRender = false;
		
		$kword = $this->params->query['term'];
		$ret = array();
		if ($res = $this->Product->find('list', array(
			'conditions' => array('Product.name LIKE' => "%{$kword}%")
		))) {
			foreach ($res as $id => $name) {
				$ret[] = array(
					'id' => $id,
					'label' => $name
				);
			}
		}
		echo json_encode($ret);
	}
	
}
